package com.example.workmode;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.example.workmode.Alarm.RegisterAlarm;
import com.example.workmode.Timing.BreakTimer;
import com.example.workmode.Timing.WorkTimer;

public class WorkModeFragment extends Fragment {
    
	private View view;
	private Button startBtn;
	private TextView showTime;
	private TextView state;
	private boolean isCounting = false;
	private int duration = 5;
	private BroadcastReceiver myReceiver;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_main, container, false);
		showTime = (TextView) view.findViewById(R.id.showTime);
		state = (TextView) view.findViewById(R.id.state);
		startBtn = (Button) view.findViewById(R.id.startStopBtn);
        
		startBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {

				// start or stop timer
				Intent timerIntent = new Intent(view.getContext(), WorkTimer.class);
				Intent breakTimerIntent = new Intent(view.getContext(), BreakTimer.class);
				if (isCounting) {
					isCounting = false;
					view.getContext().stopService(timerIntent);
					view.getContext().stopService(breakTimerIntent);
					//startBtn.setText("START");
					startBtn.setBackgroundResource(R.drawable.startbtn);
					state.setText("");
					showTime.setText("0:00");
				} else {
					isCounting = true;
					view.getContext().startService(timerIntent);
					//startBtn.setText("STOP");
					startBtn.setBackgroundResource(R.drawable.stopbtn);
				}
				
			}
			
		});
		
		/*
		Intent i = new Intent(view.getContext(), RegisterAlarm.class);
		i.putExtra("msg", "regAgain");
		view.getContext().sendBroadcast(i);
		*/
		return view;
	}
	
	@Override
	public void onResume() {
    	super.onResume();
    	IntentFilter intentFilter = new IntentFilter("showTime");
    	myReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				String status = intent.getStringExtra("state");
				String timer = intent.getStringExtra("timer");
				state.setText(status);
				showTime.setText(timer);
			}
		};
		view.getContext().registerReceiver(myReceiver, intentFilter);
    }
    
    @Override
	public void onPause() {
    	super.onPause();
    	view.getContext().unregisterReceiver(this.myReceiver);
    }
	
}
